package com.gc.business.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Console;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gc.business.domain.InventoryInfo;
import com.gc.business.domain.InventoryPrice;
import com.gc.business.domain.PartApplication;
import com.gc.business.mapper.PartApplicationMapper;
import com.gc.business.service.IInventoryInfoService;
import com.gc.business.service.IInventoryPriceService;
import com.gc.business.service.IInventoryRecordService;
import com.gc.business.service.IPartApplicationService;
import com.gc.common.constant.BusinessConstants;
import com.gc.common.utils.MoneyUtils;
import com.gc.common.utils.StringUtils;
import com.gc.system.domain.SysUser;
import com.gc.system.service.ISysUserService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 配件申请 服务层实现
 * 
 * @author liujinteng
 * @date 2020-12-03
 */
@Slf4j
@Service
public class PartApplicationServiceImpl extends ServiceImpl<PartApplicationMapper, PartApplication> implements IPartApplicationService {


    @Autowired
    private IInventoryInfoService inventoryInfoService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IInventoryPriceService inventoryPriceService;

    @Autowired
    private IInventoryRecordService inventoryRecordService;

    @Override
    public List<PartApplication> list(PartApplication partApplication,List<Long> collect){
        LambdaQueryWrapper<PartApplication> wrapper = new LambdaQueryWrapper<>();
        if(partApplication != null){
            if(StringUtils.isNotEmpty(partApplication.getPartId())){
                wrapper.eq(PartApplication::getPartId, partApplication.getPartId());
            }
            if(StringUtils.isNotEmpty(partApplication.getSizeId())){
                wrapper.eq(PartApplication::getSizeId, partApplication.getSizeId());
            }
            if(StringUtils.isNotEmpty(partApplication.getPriceId())){
                wrapper.eq(PartApplication::getPriceId, partApplication.getPriceId());
            }
            if(StringUtils.isNotEmpty(partApplication.getPartName())){
                wrapper.like(PartApplication::getPartName, partApplication.getPartName());
            }
            if(StringUtils.isNotEmpty(partApplication.getPartTotal())){
                wrapper.eq(PartApplication::getPartTotal, partApplication.getPartTotal());
            }
            /*if(StringUtils.isNotEmpty(partApplication.getPartUnit())){
                wrapper.like(PartApplication::getPartUnit, partApplication.getPartUnit());
            }*/
            if(StringUtils.isNotEmpty(partApplication.getUserId())){
                wrapper.eq(PartApplication::getUserId, partApplication.getUserId());
            }
            if(StringUtils.isNotEmpty(partApplication.getReceivePeople())){
                wrapper.like(PartApplication::getReceivePeople, partApplication.getReceivePeople());
            }
            if(StringUtils.isNotEmpty(partApplication.getReceiveDate())){
                wrapper.eq(PartApplication::getReceiveDate, partApplication.getReceiveDate());
            }
            if(StringUtils.isNotEmpty(partApplication.getReceiveNum())){
                wrapper.eq(PartApplication::getReceiveNum, partApplication.getReceiveNum());
            }
            if(StringUtils.isNotEmpty(partApplication.getProjectName())){
                wrapper.like(PartApplication::getProjectName, partApplication.getProjectName());
            }
            if(StringUtils.isNotEmpty(partApplication.getAuditStatus())){
                wrapper.eq(PartApplication::getAuditStatus, partApplication.getAuditStatus());
            }
            if(StringUtils.isNotEmpty(partApplication.getRejectCause())){
                wrapper.like(PartApplication::getRejectCause, partApplication.getRejectCause());
            }
            if(StringUtils.isNotEmpty(partApplication.getApproveId())){
                wrapper.eq(PartApplication::getApproveId, partApplication.getApproveId());
            }
            if(StringUtils.isNotEmpty(partApplication.getRecordId())){
                wrapper.eq(PartApplication::getRecordId, partApplication.getRecordId());
            }
            if(StringUtils.isNotEmpty(partApplication.getCreateBy())){
                wrapper.like(PartApplication::getCreateBy, partApplication.getCreateBy());
            }
            if(StringUtils.isNotEmpty(partApplication.getCreateTime())){
                wrapper.eq(PartApplication::getCreateTime, partApplication.getCreateTime());
            }
            if(StringUtils.isNotEmpty(partApplication.getUpdateBy())){
                wrapper.like(PartApplication::getUpdateBy, partApplication.getUpdateBy());
            }
            if(StringUtils.isNotEmpty(partApplication.getUpdateTime())){
                wrapper.eq(PartApplication::getUpdateTime, partApplication.getUpdateTime());
            }
            if(StringUtils.isNotEmpty(partApplication.getRemark())){
                wrapper.like(PartApplication::getRemark, partApplication.getRemark());
            }
            if(StringUtils.isNotEmpty(partApplication.getInventoryId())){
                wrapper.eq(PartApplication::getInventoryId, partApplication.getInventoryId());
            }
            if(CollUtil.isNotEmpty(collect)){
                //库存
                wrapper.in(PartApplication::getInventoryId, collect);
            }
        }
        return baseMapper.selectList(wrapper);
    }


    @Override
    public List<PartApplication> selectPartApplicationList(Long userId,String reviewType,Integer pageNum, Integer pageSize) {
        List<PartApplication> partApplicationList = new ArrayList<>();
        //查询用户角色列
        String userRoles = sysUserService.selectUserRole(userId);

        //该公司下的所有库存
        SysUser sysUser = sysUserService.selectUserById(userId);
        InventoryInfo inventoryInfo = new InventoryInfo();
        inventoryInfo.setAttrId(sysUser.getAttrId());
        List<InventoryInfo> inventoryInfoList = inventoryInfoService.list(inventoryInfo);
        if (CollUtil.isEmpty(inventoryInfoList) || inventoryInfoList.size() == 0){
            return partApplicationList;
        }

        //库存IDs
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < inventoryInfoList.size(); i++) {
            if (i == inventoryInfoList.size()-1){
                sb.append(inventoryInfoList.get(i).getInventoryId());
            }else {
                sb.append(inventoryInfoList.get(i).getInventoryId()+",");
            }
        }

        //判断是否为维修经理
        if(userRoles.contains(BusinessConstants.KEEP_MANAGER)){
            if(pageNum != null && pageSize != null){PageHelper.startPage(pageNum,pageSize,"create_time DESC");}
            partApplicationList = baseMapper.selectPartApplicationList(userId,reviewType,sb.toString());
        }else {
            if (reviewType.equals("0")){
                if(pageNum != null && pageSize != null){PageHelper.startPage(pageNum,pageSize,"create_time DESC");}
                partApplicationList = baseMapper.selectPartApplicationListFalse(userId,sb.toString());
            }
        }
        return partApplicationList;
    }

    @Override
    public String executeMethod(PartApplication partApplication, String auditStatus,String rejectCause) {
        if (auditStatus.equals("1")){//通过减库存
            InventoryInfo inventoryInfo = inventoryInfoService.getById(partApplication.getInventoryId());
            if (inventoryInfo == null) {
                return "1";
            }
            //查询库存中间表  查询该物品该规格下该规格值的数量
            LambdaQueryWrapper<InventoryPrice> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(InventoryPrice::getInventoryId, partApplication.getInventoryId());
            wrapper.eq(InventoryPrice::getSizeId, partApplication.getSizeId());
            wrapper.eq(InventoryPrice::getPriceId, partApplication.getPriceId());
            List<InventoryPrice> inventoryPriceList = inventoryPriceService.list(wrapper);
            if (CollUtil.isEmpty(inventoryPriceList)) {
                return "2";
            }
            //默认减第一条数据
            for (int i = 0; i < inventoryPriceList.size(); i++) {
                InventoryPrice price1 = inventoryPriceList.get(i);
                //当前为0,跳出循环
                if (price1.getItemNum().equals("0")){
                    continue;
                }else if (Integer.valueOf(price1.getItemNum()) > partApplication.getReceiveNum() ){
                    //减去库存总量与中间表数量
                    Integer totalNum = Integer.valueOf(MoneyUtils.moneySub(String.valueOf(price1.getItemNum()), String.valueOf(partApplication.getReceiveNum())));
                    price1.setItemNum(String.valueOf(totalNum));
                    inventoryPriceService.updateById(price1);
                    break;
                }else {
                    if (i == inventoryPriceList.size()){
                        return  "3";
                    }
                    Integer allCount = 0;
                    int index = 0;
                    Integer diffNum = 0;
                    for (int j = 0; j < inventoryPriceList.size(); j++) {
                        allCount = Integer.valueOf(inventoryPriceList.get(j).getItemNum())+allCount;
                        index = index +j;
                        if (allCount >= partApplication.getReceiveNum()){
                            diffNum = partApplication.getReceiveNum() -Integer.valueOf(inventoryPriceList.get(j-1).getItemNum());
                            break;
                        }
                    }
                    for (int z = 0; z < inventoryPriceList.size(); z++) {
                        if (z <= index-1){
                            InventoryPrice price2 = inventoryPriceList.get(z).setItemNum("0");
                            inventoryPriceService.updateById(price2);
                        }
                    }
                    Console.log("index:{},diffNum:{}",index,diffNum);
                    InventoryPrice inventoryPrice = inventoryPriceList.get(index);
                    Integer totalNum = Integer.valueOf(MoneyUtils.moneySub(String.valueOf(inventoryPrice.getItemNum()), String.valueOf(diffNum)));
                    inventoryPrice.setItemNum(String.valueOf(totalNum));
                    inventoryPriceService.updateById(inventoryPrice);
                    break;
                }
            }
            //库存总数量减去领取数量
            String totalCount = MoneyUtils.moneySub(inventoryInfo.getItemNum(), String.valueOf(partApplication.getReceiveNum()));
            inventoryInfo.setItemNum(totalCount);
            //库存总钱数减去领取数量*单价
            String moneySub = MoneyUtils.moneySub(inventoryInfo.getItemSum(), MoneyUtils.moneyMul(partApplication.getReceiveNum() + "", inventoryPriceList.get(0).getItemSum()));
            inventoryInfo.setItemSum(moneySub);
            inventoryInfoService.updateById(inventoryInfo);
        }else if (auditStatus.equals("2")){

            partApplication.setRejectCause(rejectCause);
            //退回  因为查询可领取的规格数量包含了 未审批  占用的数量
        }
        return "0";
    }
}
